package com.catchdays.main;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;

import com.catchdays.R;

public class SeparatedListAdapter extends BaseAdapter {
	public final static int TYPE_SECTION_HEADER = 0;

	public final ArrayAdapter<String> headers;
	public final Map<String, Adapter> sections;

	public SeparatedListAdapter(Context context) {
		headers = new ArrayAdapter<String>(context, R.layout.list_header, R.id.listHeader);
		sections = new LinkedHashMap<String, Adapter>();
	}

	public void addSection(String sectionName, Adapter adapter) {
		headers.add(sectionName);
		sections.put(sectionName, adapter);
	}

	@Override
	public int getCount() {
		int total = 0;

		for (Adapter adapter : sections.values()) {
			total += adapter.getCount() + 1;
		}

		return total;
	}

	@Override
	public Object getItem(int position) {
		for (Entry<String, Adapter> entry : sections.entrySet()) {
			Adapter adapter = (Adapter) entry.getValue();
			int size = adapter.getCount() + 1;

			if (position == 0) {
				return entry.getKey();
			} else if (position < size) {
				return adapter.getItem(position - 1);
			}

			position -= size;
		}

		return null;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public int getViewTypeCount() {
		int total = 1;

		for (Entry<String, Adapter> entry : sections.entrySet()) {
			Adapter adapter = (Adapter) entry.getValue();

			total += adapter.getViewTypeCount();
		}

		return total;
	}

	@Override
	public int getItemViewType(int position) {
		int type = 1;

		for (Entry<String, Adapter> entry : sections.entrySet()) {
			Adapter adapter = (Adapter) entry.getValue();
			int size = adapter.getCount() + 1;

			if (position == 0) {
				return TYPE_SECTION_HEADER;
			} else if (position < size) {
				return type + adapter.getItemViewType(position - 1);
			}

			position -= size;
			type += adapter.getViewTypeCount();
		}

		return -1;
	}

	@Override
	public boolean areAllItemsEnabled() {
		return false;
	}

	@Override
	public boolean isEnabled(int position) {
		return (getItemViewType(position) != TYPE_SECTION_HEADER);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		int headerPosition = 0;

		for (Entry<String, Adapter> entry : sections.entrySet()) {
			Adapter adapter = (Adapter) entry.getValue();
			int size = adapter.getCount() + 1;

			if (position == 0) {
				return headers.getView(headerPosition, convertView, parent);
			} else if (position < size) {
				return adapter.getView(position - 1, convertView, parent);
			}

			position -= size;
			headerPosition++;
		}

		return null;
	}
}
